package cn.itzzx.lagou.service.impl;

import cn.itzzx.lagou.dao.LagouAuthCodeMapper;
import cn.itzzx.lagou.pojo.LagouAuthCode;
import cn.itzzx.lagou.service.CodeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * TODO
 *
 * @author Martin
 * @since 1.0
 */
@Service
public class CodeServiceImpl implements CodeService {

    @Resource
    private LagouAuthCodeMapper lagouAuthCodeMapper;

    @Override
    public int insertCode(String code, String email) {
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setCode(code);
        Date now = new Date();
        Date expiretime = new Date(now.getTime() + 600000);
        lagouAuthCode.setCreatetime(now);
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setExpiretime(expiretime);
        int result = lagouAuthCodeMapper.insert(lagouAuthCode);
        return result;
    }

    @Override
    public Integer validateCode(String email, String code) {
        //根据邮箱获取验证码 取最新一条的 order by createtime desc limit 1
        LagouAuthCode lagouAuthCode = lagouAuthCodeMapper.selectCodeByEmail(email);

        if(lagouAuthCode == null){
            return 1;
        }
        if(!code.equals(lagouAuthCode.getCode())){
            return 1;
        }
        //验证是否超时
        Date date = new Date();
        if(date.compareTo(lagouAuthCode.getExpiretime())==1){
            return 2;
        }
        return 0;
    }
}
